package ru.spb.xmlreshelper.screen.database;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ru.spb.xmlreshelper.XmlResHelper;
import ru.spb.xmlreshelper.database.DatabaseManager;
import ru.spb.xmlreshelper.domain.DatabaseException;
import ru.spb.xmlreshelper.domain.ICdtService;
import ru.spb.xmlreshelper.gui.InvalidArgumentError;

import java.util.Map;

/**
 * @author Nikita.Brazhnikov
 */
public class DatabaseConnectionController {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseConnectionController.class);

    public void test(Map<String, String> connectionParams) throws InvalidArgumentError {
        logger.debug("Connection test started");
        System.out.println("Connection test started");
        String url = connectionParams.get("URL");
        String sid = connectionParams.get("SID");
        String user = connectionParams.get("User");
        String port = connectionParams.get("Port");
        String pass = connectionParams.get("Password");
        check(url, "URL");
        check(sid, "SID");
        check(port, "Port");
        DatabaseManager manager = DatabaseManager.getInstance();
        manager.setUrl(url);
        manager.setPort(port);
        manager.setSid(sid);
        manager.setUsername(user);
        manager.setPassword(pass);
        try {
            ICdtService service = XmlResHelper.getService(ICdtService.class);
            service.updateCdts();
            logger.debug("Connection test successfully finished");
        } catch (DatabaseException e) {
            logger.warn("Can not establish connection", e);
            throw e;
        } catch (Exception e) {
            logger.warn("Can not establish connection", e);
            throw new RuntimeException(e);
        }
    }

    protected void check(String value, String valueLabel) throws InvalidArgumentError {
        if (StringUtils.isBlank(value))
            throw new InvalidArgumentError("Required argument %s is not specified", valueLabel);
    }

}
